package com.coldchain.gate.filter;

import com.coldchain.authclient.config.ServiceAuthConfig;
import com.coldchain.authclient.config.UserAuthConfig;
import com.coldchain.authclient.jwt.ServiceAuthUtil;
import com.coldchain.authclient.jwt.UserAuthUtil;
import com.coldchain.common.constant.RequestHeaderConstants;
import com.coldchain.gate.route.RouteDynamicFilterUtils;
import com.fangliai.core.context.BaseContextHandler;
import com.fangliai.core.util.jwt.IJWTInfo;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;


@Component
public class AdminAccessFilter extends ZuulFilter {
    private final static Logger log= LoggerFactory.getLogger(AdminAccessFilter.class);
    @Value("${gate.ignore.startWith}")
    private String startWith;
    @Value("${zuul.prefix}")
    private String zuulPrefix;
    @Autowired
    private UserAuthUtil userAuthUtil;
    @Autowired
    private ServiceAuthConfig serviceAuthConfig;
    @Autowired
    private UserAuthConfig userAuthConfig;
    @Autowired
    private ServiceAuthUtil serviceAuthUtil;
    @Override
    public String filterType() {
        return "pre";
    }
    @Override
    public int filterOrder() {
        return 1;
    }
    @Override
    public boolean shouldFilter() {
        return true;
    }
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        final String requestUri = request.getRequestURI().substring(zuulPrefix.length());
        final String method = request.getMethod();
        BaseContextHandler.setToken(null);
        // 不进行拦截的地址
        if (isStartWith(requestUri)) {
            return null;
        }
        if(RouteDynamicFilterUtils.ignore(requestUri)){
            return  null;
        }
//        IJWTInfo user = null;
//
//        try {
//            user = getJWTUser(request, ctx);
//        } catch (Exception e) {
//            setFailedRequest(JSON.toJSONString(new Exception("用户身份过期,请重新登录!")), HttpStatus.UNAUTHORIZED.value());
//
//            return null;
//        }
        String authToken = request.getHeader(userAuthConfig.getTokenHeader());
        if (StringUtils.isBlank(authToken)) {
            authToken = request.getParameter("token");
        }
        if(StringUtils.isBlank(authToken) &&  request.getCookies()!=null){
            for (Cookie co:request.getCookies()){
                if("token".equals(co.getName())){
                    authToken = co.getValue();
                }
            }
        }
        if(!StringUtils.isEmpty(authToken)){
            ctx.addZuulRequestHeader(userAuthConfig.getTokenHeader(), authToken);
        }
        //@TODO delete
        System.out.println("USER_TOKEN:"+authToken);
        BaseContextHandler.setToken(authToken);
        // 申请客户端密钥头
        ctx.addZuulRequestHeader(serviceAuthConfig.getTokenHeader(), serviceAuthUtil.getClientToken());
        return null;
    }

    /**
     * 返回session中的用户信息
     *
     * @param request
     * @param ctx
     * @return
     */
    private IJWTInfo getJWTUser(HttpServletRequest request, RequestContext ctx) throws Exception {
        String authToken = request.getHeader(userAuthConfig.getTokenHeader());
        String originToken = null;
        if (StringUtils.isBlank(authToken)) {
            authToken = request.getParameter("token");
        }
        if(StringUtils.isBlank(authToken)){
            for (Cookie co:request.getCookies()){
                if("token".equals(co.getName())){
                    authToken = co.getValue();
                }
            }
        }
        if (authToken != null && authToken.startsWith(RequestHeaderConstants.JWT_TOKEN_TYPE)) {
            originToken = authToken;
            authToken = authToken.substring(RequestHeaderConstants.JWT_TOKEN_TYPE.length(),authToken.length());
        }
        ctx.addZuulRequestHeader(userAuthConfig.getTokenHeader(), originToken);
        BaseContextHandler.setToken(originToken);
        return userAuthUtil.getInfoFromToken(authToken);
    }

    /**
     * URI是否以什么打头
     *
     * @param requestUri
     * @return
     */
    private boolean isStartWith(String requestUri) {
        boolean flag = false;
        for (String s : startWith.split(",")) {
            if (requestUri.startsWith(s)) {
                return true;
            }
        }
        return flag;
    }

    /**
     * 网关抛异常
     * @param body
     * @param code
     */
    private void setFailedRequest(String body, int code) {
        log.debug("Reporting error ({}): {}", code, body);
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.setResponseStatusCode(code);
        if (ctx.getResponseBody() == null) {
            ctx.setResponseBody(body);
            ctx.setSendZuulResponse(false);
            ctx.getResponse().setContentType("text/html;charset=UTF-8");
        }
    }

}
